
from flask import request, jsonify, Blueprint
from sqlalchemy import null
from app.util.jwtUtil import generate_token, decode_token, get_user_id_from_token
from app.enums import ErrorCode
from app.service import userService

user_bp = Blueprint('user', __name__)

@user_bp.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    user_id = data.get('userId')
    password = data.get('password')
    user = userService.get_login_by_userid(user_id)
    if not user or user.password != password:
        return jsonify({'code': ErrorCode.USER_PASSWORD_ERROR.code, 'msg': ErrorCode.USER_PASSWORD_ERROR.msg}), 401
    token = generate_token(user_id)
    return jsonify({'code': ErrorCode.SUCCESS.code, 'msg': '登录成功', 'token': token})

@user_bp.route('/new_account', methods=['POST'])
def new_account():
    data = request.get_json()
    user_id = data.get('userId')
    username = data.get('username')
    password = data.get('password')
    age = data.get('age')
    phone = data.get('phone')

    if userService.get_login_by_userid(user_id):
        return jsonify({'code': ErrorCode.USER_ALREADY_EXISTS.code, 'msg': ErrorCode.USER_ALREADY_EXISTS.msg}), 400

    # 将新的字段传递给 service 层
    #def create_user(user_id, username, password, age, phone, introduce=None):
    success = userService.create_user(user_id,username,password,age,phone,None)

    if success:
        return jsonify({'code': ErrorCode.SUCCESS.code, 'msg': '注册成功'})
    else:
        # 如果 service 返回 False，表示创建失败
        return jsonify({'code': ErrorCode.SERVER_ERROR.code, 'msg': '注册失败'}), 500 # 可以使用更具体的错误码

@user_bp.route('/user_info', methods=['GET'])
def get_user_info():
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code, 'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401
    user = userService.get_user_by_userid(user_id)
    if not user:
        return jsonify({'code': ErrorCode.USER_NOT_FOUND.code, 'msg': ErrorCode.USER_NOT_FOUND.msg}), 404
    return jsonify({'code': ErrorCode.SUCCESS.code, 'msg': '获取成功', 'data': {

        'userId': user.userid,
        'username': user.username,
        'age': user.age,
        'phone': user.phone,
        'introduce': user.introduce
    }})

@user_bp.route('/user', methods=['PUT'])
def update_user():
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code, 'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401
    data = request.get_json()
    user = userService.get_user_by_userid(user_id)
    if not user:
        return jsonify({'code': ErrorCode.USER_NOT_FOUND.code, 'msg': ErrorCode.USER_NOT_FOUND.msg}), 404
    # 只允许更新部分字段
    if 'username' in data:
        user.username = data['username']
    if 'age' in data:
        user.age = data['age']
    if 'phone' in data:
        user.phone = data['phone']
    if 'introduce' in data:
        user.introduce = data['introduce']
    # 移除了错误的密码更新行
    userService.update_user(user)
    return jsonify({'code': ErrorCode.SUCCESS.code, 'msg': '更新成功'})

@user_bp.route('/user/password', methods=['PUT'])
def update_password():
    token = request.headers.get('Authorization')
    user_id = get_user_id_from_token(token)
    if not user_id:
        return jsonify({'code': ErrorCode.USER_TOKEN_INVALID.code, 'msg': ErrorCode.USER_TOKEN_INVALID.msg}), 401

    data = request.get_json()
    new_password = data.get('password')


    if not new_password:
        # 可以添加一个错误码表示缺少密码参数
        return jsonify({'code': ErrorCode.SERVER_ERROR.code, 'msg': '缺少密码参数'}), 400 # 使用一个通用错误码或新增一个

    # 调用 service 层更新密码
    success = userService.update_login(user_id, new_password)

    if success:
        return jsonify({'code': ErrorCode.SUCCESS.code, 'msg': '密码更新成功'})
    else:
        # 如果 service 返回 False，可能是用户不存在或其他问题
        return jsonify({'code': ErrorCode.USER_NOT_FOUND.code, 'msg': ErrorCode.USER_NOT_FOUND.msg}), 404 # 或者更具体的错误码
